package topuc.com.mvp.view;

import android.content.Context;
import android.graphics.Canvas;
import android.graphics.Paint;
import android.graphics.Rect;
import android.os.Handler;
import android.os.Message;
import android.support.annotation.Nullable;
import android.util.AttributeSet;
import android.util.Log;
import android.view.MotionEvent;
import android.view.View;
import android.widget.TextView;

import java.util.ArrayList;
import java.util.List;
import java.util.Timer;
import java.util.TimerTask;

/**
 * Created by apls on 2018/12/5.
 */
public class PickerView extends View {

    private Timer mTimer;
    private Paint mPaint;
    private List<String> mList;
    private int mColorText = 0x333333;
    private int mViewHeight;
    private int mViewWidth;
    private float mMaxTextSize=80;
    private float mMinTextSize=40;

    private float mMaxTextAlpha = 255;
    private float mMinTextAlpha = 120;

    private boolean isInit;
    private float mMoveLen;
    private List<String> mDataList;
    private int mCurrentSelected;
    private MyTimerTask mTask;
    private float mLastDownY;
    private onSelectListener mSelectListener;

    /**
     * text之间间距和minTextSize之比
     */
    public static final float MARGIN_ALPHA = 2.8f;

    /**
     * 自动回滚到中间的速度
     */
    public static final float SPEED=2;

    Handler updateHandler=new Handler(){

        @Override
        public void handleMessage(Message msg) {

            if(Math.abs(mMoveLen)<SPEED){
                mMoveLen=0;
                if(mTask!=null){
                    mTask.cancel();
                    mTask=null;
                    performSelect();
                }else{
                    //这里mMoveLen/Math.abs(mMoveLen)是为了保有mMoveLen的正负号，以实现上滚或下滚
                    mMoveLen=mMoveLen-mMoveLen/Math.abs(mMoveLen)*SPEED;
                }
            }
            invalidate();
        }
    };

    public void setOnSelectListener(onSelectListener listener){
        mSelectListener=listener;
    }

    /**
     * 执行选择事件
     */
    private void performSelect() {

        if(mSelectListener!=null){
            mSelectListener.onSelect(mDataList.get(mCurrentSelected));
        }
    }

    public PickerView(Context context) {
        super(context);

        init();
    }

    public PickerView(Context context, @Nullable AttributeSet attrs) {
        super(context, attrs);
        init();
    }

    /**
     * 初始化数据
     */
    private void init() {

        mTimer=new Timer();
        mPaint=new Paint(Paint.ANTI_ALIAS_FLAG);
        mPaint.setStyle(Paint.Style.FILL);
        mPaint.setTextAlign(Paint.Align.CENTER);
        mPaint.setColor(mColorText);
        mList=new ArrayList<>();
    }

    @Override
    protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
        super.onMeasure(widthMeasureSpec, heightMeasureSpec);

        mViewHeight=getMeasuredHeight();
        mViewWidth=getMeasuredWidth();

        mMaxTextSize=mViewHeight/4.0f;
        mMinTextSize=mMaxTextSize/2;
        isInit=true;
        invalidate();

    }

    @Override
    protected void onLayout(boolean changed, int left, int top, int right, int bottom) {
        super.onLayout(changed, left, top, right, bottom);
    }

    @Override
    protected void onDraw(Canvas canvas) {
        super.onDraw(canvas);

        if(isInit) drawData(canvas);
    }

    @Override
    public boolean onTouchEvent(MotionEvent event) {

        switch (event.getAction()){

            case MotionEvent.ACTION_DOWN:

                doDown(event);
                break;

            case MotionEvent.ACTION_MOVE:

                doMove(event);
                break;

            case MotionEvent.ACTION_UP:

                doUp(event);
                break;
        }

        return true;
    }

    /**
     * @param event
     */
    private void doUp(MotionEvent event) {

        //抬手后mCurrentSelected的位置由当前位置move到中间选中位置
        if(Math.abs(mMoveLen)<0.0001){
            mMoveLen=0;
            return;
        }

        if(mTask!=null){
            mTask.cancel();
            mTask=null;
        }

        mTask=new MyTimerTask(updateHandler);
        mTimer.schedule(mTask,0,10);
    }

    /***
     * @param event
     */
    private void doMove(MotionEvent event) {

        mMoveLen=mMoveLen+(event.getY()-mLastDownY);

        if(mMoveLen>MARGIN_ALPHA*mMinTextSize/2){
            //往下滑超过离开距离
            moveTailToHead();
            mMoveLen=mMoveLen-MARGIN_ALPHA*mMinTextSize;
        }else if(mMoveLen<-MARGIN_ALPHA*mMinTextSize/2){
            //往上滑超过离开距离
            moveHeadToTail();
            mMoveLen=mMoveLen+MARGIN_ALPHA*mMinTextSize;
        }

        mLastDownY=event.getY();
        invalidate();
    }

    private void doDown(MotionEvent event){

        if(mTask!=null){
            mTask.cancel();
            mTask=null;
        }
        mLastDownY=event.getY();
    }

    /**
     * @param datas
     */
    public void setData(List<String> datas){

        mDataList=datas;
        mCurrentSelected=datas.size()/2;
        invalidate();
    }

    /**
     *
     */
    private void moveHeadToTail() {
        String head = mDataList.get(0);
        mDataList.remove(0);
        mDataList.add(head);
    }

    private void moveTailToHead() {
        String tail = mDataList.get(mDataList.size() - 1);
        mDataList.remove(mDataList.size() - 1);
        mDataList.add(0, tail);
    }

    /**
     * @param canvas
     */
    private void drawData(Canvas canvas) {

        // 先绘制选中的text再往上往下绘制其余的text
        float scale = parabola(mViewHeight / 4.0f, mMoveLen);

        Log.d("PickerView","scale:"+scale);
        //字体大小渐变
        float size = (mMaxTextSize - mMinTextSize) * scale + mMinTextSize;

        mPaint.setTextSize(size);
        int alpha= (int) ((mMaxTextAlpha-mMinTextAlpha) * scale+mMinTextAlpha);
        mPaint.setAlpha(alpha);

        float x= (float) (mViewWidth/2.0);
        float y= (float) (mViewHeight/2.0+mMoveLen);
        Paint.FontMetricsInt fmi = mPaint.getFontMetricsInt();
        float baseline = (float) (y- (fmi.bottom / 2.0 + fmi.top / 2.0));
        canvas.drawText(mDataList.get(mCurrentSelected),x,baseline,mPaint);
        //绘制上方data
        for(int i=1;(mCurrentSelected-i)>=0;i++){
            drawOtherText(canvas,i,-1);
        }
        //绘制下方data
        for(int i=1;(mCurrentSelected+i)<mDataList.size();i++){
            drawOtherText(canvas,i,1);
        }
    }

    /**
     * @param canvas
     * @param position:距离mCurrentSelected的差值
     * @param type:1表示向下绘制，-1表示向上绘制
     */
    private void drawOtherText(Canvas canvas,int position,int type){

        float d=MARGIN_ALPHA*mMinTextSize*position+type*mMoveLen;
        float scale=parabola(mViewHeight/4.0f,d);

        Log.d("PickerView","scale:"+scale);

        float size=(mMaxTextSize-mMinTextSize)*scale+mMinTextSize;

        mPaint.setTextSize(size);
        int alpha= (int) ((mMaxTextAlpha-mMinTextAlpha)*scale+mMinTextAlpha);
        mPaint.setAlpha(alpha);

        float y= (float) (mViewHeight/2.0+type*d);
        Paint.FontMetricsInt fmi=mPaint.getFontMetricsInt();
        float baseline= (float) (y-(fmi.bottom/2.0+fmi.top/2.0));

        canvas.drawText(mDataList.get(mCurrentSelected+type*position),(float)(mViewWidth/2.0),baseline,mPaint);
    }

    /**
     * 抛物线
     * @param zero 零点坐标
     * @param x 偏移量
     * @return scale
     */
    private float parabola(float zero, float x)
    {
        float f = (float) (1 - Math.pow(x / zero, 2));
        return f < 0 ? 0 : f;
    }

    class MyTimerTask extends TimerTask {

        Handler handler;

        public MyTimerTask(Handler handler){
            this.handler=handler;
        }

        @Override
        public void run() {

            handler.sendMessage(handler.obtainMessage());
        }
    }

    public interface onSelectListener{

        void onSelect(String text);
    }

}
